package com.day240701.controller;

import com.alibaba.fastjson2.JSON;
import com.day240701.dao.StudentDao;
import com.day240701.entity.Admin;
import com.day240701.entity.Student;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "AjaxServlet", value = "/AjaxServlet")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getParameter("op");
        System.out.println("op=" + op);
        if ("test1".equals(op)) {
            test1(request,response);
        } else if ("test2".equals(op)) {
            test2(request, response);
        } else if ("queryAllStudents".equals(op)) {
            queryAllStudents(request, response);
        }

    }
    protected void test1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 和之前一样  request 获取请求参数
        System.out.println(request.getParameter("sNo"));
        System.out.println(request.getParameter("sName"));

        // 返回数据 响应数据
        // 不同的是: 返回数据变了，通过 IO 的方式向浏览器输出数据(out.println)
        PrintWriter out = response.getWriter();
        out.println("通过 out 对象，向浏览器 输出数据");
        out.flush(); // 传输完毕，刷新一下
        out.close(); // 并关闭当前out对象
    }

    protected void test2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Admin> list = new ArrayList<>();
        list.add(new Admin(1, "wwy1"));
        list.add(new Admin(2, "wwy2"));
        list.add(new Admin(3, "wwy3"));
        // [{"aName":"wwy1","aNo":1},{"aName":"wwy2","aNo":2},{"aName":"wwy3","aNo":3}]
        String msg = JSON.toJSONString(list);
        System.out.println(msg);

        PrintWriter out = response.getWriter();
        out.println(msg);
        out.flush();
        out.close();
    }

    protected void queryAllStudents(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StudentDao studentDao = new StudentDao();
        List<Student> list = studentDao.queryAllStudents();
        String listString = JSON.toJSONString(list);
        try{
            Thread.sleep(5000);
        }catch (Exception e){
            e.printStackTrace();
        }

        PrintWriter out = response.getWriter();
        out.println(listString);
        out.flush();
        out.close();
    }
}
